type TodoItem = {
  id: number
  text: string
  done: boolean
}

type ActionType =
  { type: 'add'; payload: string } // type 表示的是任务的类型，payload指的是传递过来的参数
  | { type: 'toggle'; payload: TodoItem['id'] }
  | { type: 'delete'; payload: TodoItem['id'] }
  | { type: 'loadData'; payload: TodoItem[] }

export const initialState = [{ id: 1, text: '吃饭', done: false }]

export const reducer = (state: TodoItem[], action: ActionType) => {
  switch (action.type) {
    case 'add':
      const newId = state.length === 0 ? 1 : state[state.length - 1].id + 1
      return [
        ...state,
        {
          id: newId,
          text: action.payload,
          done: false
        }
      ]
    case 'toggle':
      return state.map(todo => {
        if (todo.id === action.payload) {
          return {
            ...todo,
            done: !todo.done
          }
        }
        return todo
      })
    case 'delete':
      return state.filter(item => {
        return item.id !== action.payload
      })
    case 'loadData':
      return action.payload
    default:
      return state
  }
}